<?php
/**
 * Zend Framework application
 *
 * @category     Application
 * @package      Admin
 * @subpackage   Validate
 * @author       Krzysztof Kardasz <krzysztof.kardasz@gmail.com>
 * @copyright    Copyright (c) 2010 Krzysztof Kardasz
 */

/**
 * Walidacja, nazwa tagu
 *
 * @category     Application
 * @package      Admin
 * @subpackage   Validate
 * @author       Krzysztof Kardasz <krzysztof.kardasz@gmail.com>
 * @copyright    Copyright (c) 2010 Krzysztof Kardasz
 * @version 	 1.0
 */
class Hesperos_Validator_TagName extends Zend_Validate_Abstract
{

    /**
     * Wiadomości błędów
     */
    const MSG_EXISTS  = 'msgExists';

    /**
     * Wiadomości błędów
     *
     * @var array
     */
    protected $_messageTemplates = array(
        self::MSG_EXISTS  => 'Tag "%value%" exists'
    );

    /**
     * Walidacja
     *
     * @param string $value wartość
     * @return boolean
     */
    public function isValid ($value, $context = null)
    {
        $this->_setValue($value);

        $id        = null;
        $language  = null;
        if (is_array($context)) {
            $id        = (isset($context['frm_id'])) ? $context['frm_id'] : null;
            $language  = (isset($context['frm_le'])) ? $context['frm_le'] : null;
        }


        $table = new Application_Model_Gateway_Table_Tag ();

        $select = $table->select()->from($table->getTableName(), array(new Zend_Db_Expr('COUNT(*)')));
        $select->where('name = ?', $value);

        if($id && $language) {
            $cond1 = $table->getAdapter()->quoteInto('id != ?', $id);
            $cond2 = implode(' AND ', array(
                $table->getAdapter()->quoteInto('id = ?', $id),
                $table->getAdapter()->quoteInto('language != ?', $language)
            ));

            $select->where(implode (' OR ', array(
                '(' . $cond1 . ')',
                '(' . $cond2 . ')'
            )));
        }

        if ($select->query()->fetchColumn() != 0) {
            $this->_error(self::MSG_EXISTS);
            return false;
        }

        return true;
    }
}